package com.zhijiaoyun.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shisfish.util.EmailUitl;
import com.shisfish.util.EmailUtils;
import com.zhijiaoyun.common.*;
import com.zhijiaoyun.controller.base.BaseController;
import com.zhijiaoyun.model.*;
import com.zhijiaoyun.model.dto.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Controller
@RequestMapping(value = "/api/user", produces = "application/json; charset=utf-8")
public class UserApi extends BaseController {

    /**
     * 用户登录
     *
     * @param email
     * @param password
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login")
    public Map<String, Object> login(@RequestParam String email, @RequestParam String password, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmptyString(email)) {
            return responseLoginError();
        }
        try {
            email = URLDecoder.decode(email, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return responseLoginError();
        }
        if (StringUtils.isEmptyString(password)) {
            return responseLoginError();
        }
        return loginService.userLogin(email, password, "browser", request, response);
    }

    // 手机号，邮箱唯一验证
    @ResponseBody
    @RequestMapping(value = "/email", method = RequestMethod.POST)
    public Map<String, Object> email(String email) {
        Map<String, Object> map = new HashMap<>();

        User user = userService.getUserByEmail(email);
        if (user != null) {
            map.put(DsConstant.CODE, DsConstant.CODE_EMAIL_EXIST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_EMAIL_EXIST);
            return map;
        }
        try {
            EmailUitl.sendEmail1(email);
            map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(DsConstant.CODE, DsConstant.CODE_EMAIL_SEND_ERROR);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_EMAIL_SEND_ERROR);
            return map;
        }

        return map;

    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Map<String, Object> addUser(String username, String realname, String email, String mobile, String password,
                                       Integer sex, String birthday, Long schoolId, Long academyId, Long majorId, Integer status,
                                       Integer vipStatus) {
        Map<String, Object> map = new HashMap<>();

        User user = userService.getUserByUsername(username);
        if (user != null) {
            map.put(DsConstant.CODE, DsConstant.CODE_USERNAME_EXIST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USERNAME_EXIST);
            return map;
        }
        user = userService.getUserByEmail(email);
        if (user != null) {
            map.put(DsConstant.CODE, DsConstant.CODE_EMAIL_EXIST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_EMAIL_EXIST);
            return map;
        }
        user = new User();
        user.setUsername(username);
        user.setRealname(realname == null ? "" : realname);
        user.setPassword(CommonUtils.MD5(password));
        user.setSex(sex == null ? 0 : sex);
        user.setStatus(status == null ? 0 : status);

        try {
            String code = EmailModal.createCode(email, user);
            String content = EmailModal.createRegisterModal(Base64.getEncoder().encodeToString(code.getBytes()));
            EmailUtils.sendEmail(email, content);
            map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        } catch (Exception e) {
            map.put(DsConstant.CODE, DsConstant.CODE_EMAIL_SEND_ERROR);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_EMAIL_SEND_ERROR);
            e.printStackTrace();
            return map;
        }
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public void addUser(String action, String code, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        if (DsConstant.EMAIL.equals(action)) {
            String decode = new String(Base64.getDecoder().decode(code));
            System.out.println(decode);
            JSONObject jsonObject = JSONObject.parseObject(decode);
            String email = jsonObject.getString("email");
            User user = userService.getUserByEmail(email);
            if (user == null) {
                long expDate = jsonObject.getLongValue("expDate");
                if (new Date().before(new Date(expDate))) {
                    String username = jsonObject.getString("username");
                    String realname = jsonObject.getString("realname");
                    String password = jsonObject.getString("password");
                    int sex = jsonObject.getIntValue("sex");
                    int status = jsonObject.getIntValue("status");

                    user = new User(username, realname, password, "", email, sex, "", 0L, 0L, 0L, status, 0);
                    userService.addUser(user);
                    map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
                } else {
                    map.put(DsConstant.CODE, DsConstant.CODE_LINK_LOST);
                    map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_LINK_LOST);
                }
            } else {
                map.put(DsConstant.CODE, DsConstant.CODE_EMAIL_EXIST);
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_EMAIL_EXIST);
            }
        }

        String json = JSON.toJSONString(map);

        String html = HtmlModal.getHtmlModal(json, HtmlModal.REGISTER);

        CommonUtils.responseOutHtml(response, html);
    }

    @ResponseBody
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public Map<String, Object> userDetail(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        User user = userService.getUserByUserId(userId);
        if (user == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_USER_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USER_LOST);
            return map;
        }
        user.setPassword("");
        map.put("obj", user);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/headImg", method = RequestMethod.POST)
    public Map<String, Object> headImg(HttpServletRequest request, @RequestParam("headImg") MultipartFile headImg) {
        Map<String, Object> map = new HashMap<>();

        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        // 图片上传地址
        String pictureStr = "";
        if (headImg != null && !headImg.isEmpty()) {
            pictureStr = FileUtils.saveUserHeadImg(headImg);
            if ("".equals(pictureStr)) {
                map.put(DsConstant.CODE, DsConstant.CODE_PICTURE_NOT_NULL);
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_PICTURE_NOT_NULL);
                return map;
            }
        }
        User user = userService.getUserByUserId(userId);
        if (user == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_USER_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USER_LOST);
            return map;
        }
        user.setHeadImg(pictureStr);

        userService.updataUser(user);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    // 修改
    @ResponseBody
    @RequestMapping(value = "/modifyUser", method = RequestMethod.POST)
    public Map<String, Object> modifyUser(String username, String realname, Integer sex, String birthday,
                                          HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        User user = userService.getUserByUserId(userId);
        if (user == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_USER_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USER_LOST);
            return map;
        }
        if (!StringUtils.isEmptyString(username)) {
            User temp = userService.getUserByUsernameNotUserId(userId, username);
            if (temp != null) {
                map.put(DsConstant.CODE, DsConstant.CODE_USERNAME_EXIST);
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USERNAME_EXIST);
                return map;
            }
            user.setUsername(username);
        }

        if (!StringUtils.isEmptyString(birthday)) {
            int age = DateUtils.getAge(birthday);
            user.setAge(age);
            user.setBirthday(birthday);
        }

        if (!StringUtils.isEmptyString(realname)) {
            user.setRealname(realname);
        }

        userService.updataUser(user);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/changePassword")
    public Map<String, Object> changePassword(String oldPassword, String newPassword, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        User user = userService.getUserByUserId(userId);
        if (user == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_USER_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USER_LOST);
            return map;
        }

        if (!user.getPassword().equals(CommonUtils.MD5(oldPassword))) {
            map.put(DsConstant.CODE, DsConstant.CODE_OLD_PASSWORD_ERROR);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_OLD_PASSWORD_ERROR);
            return map;
        }

        user.setPassword(CommonUtils.MD5(newPassword));

        userService.updataUser(user);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/{courseId}/addLearnHistory")
    public Map<String, Object> addLearnHistory(@PathVariable("courseId") Long courseId, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();


        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        // 判断课程存不存在
        Course course = courseService.getCourseByCourseId(courseId);
        if (course == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_COURSE_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_COURSE_LOST);
            return map;
        }

        // 若是点击一个课程，按钮 进行学习，则添加该课程的各个课时
        CourseHistory courseHistory = courseHistoryService.getCourseHistoryByCourseIdUserId(courseId, userId);
        if (courseHistory == null) {
            // 添加课程学习
            courseHistory = new CourseHistory(userId, courseId, 1, 0D);
            courseHistoryService.addCourseHistory(courseHistory);
        }

        // 点击课程的时候的事情，添加所有课时，若用户点击之后，管理员又新增了某个课时
        // 则当添加的时候，向所有用户添加？不适用
        // 在用户的界面，添加课时学习的按钮，用户点击了，则新增该课时的学习记录
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;

    }

    // 具体某节课的修改
    @ResponseBody
    @RequestMapping(value = "/{courseId}/{lessonId}/modifyLearnHistory")
    public Map<String, Object> modifyLearnHistory(@PathVariable("courseId") Long courseId,
                                                  @PathVariable("lessonId") Long lessonId, Double schedule, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        map.put(DsConstant.CODE, 1);

        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        // 判断课是否存在
        Lesson lesson = lessonService.getLessonByLessonId(lessonId);
        if (lesson == null) {
            return map;
        }

        LearnHistory learnHistory = learnHistoryService.getLearnHistoryByLessonIdUserId(lessonId, userId);
        if (learnHistory == null) {
            // 沒有学习记录，则添加
            learnHistory = new LearnHistory(userId, courseId, lessonId);
            learnHistoryService.addLearnHistory(learnHistory);
            CourseHistory courseHistory = courseHistoryService.getCourseHistoryByCourseIdUserId(courseId, userId);
            if (courseHistory == null) {
                courseHistory = new CourseHistory(userId, courseId, 1, 0D);
                courseHistoryService.addCourseHistory(courseHistory);
            }
        } else {
            if (schedule != null) {
                learnHistory.setSchedule(schedule);
                // 如果进度为100，则学习完成
                if (schedule.doubleValue() == 1) {
                    learnHistory.setStatus(2);
                }
                learnHistoryService.modifyLearnHistory(learnHistory);

                // TODO 总体的进度的变化
                // 找到全部的LearnHistoryDto
                List<LearnHistoryDto> learnHistories = learnHistoryService.getLearnHistoryDtoByParams(userId, courseId);
                if (!StringUtils.isEmptyList(learnHistories)) {

                    CourseHistory courseHistory = courseHistoryService.getCourseHistoryByCourseIdUserId(courseId,
                            userId);
                    if (courseHistory == null) {
                        courseHistory = new CourseHistory(userId, courseId, 1, 0D);
                        courseHistoryService.addCourseHistory(courseHistory);
                    } else {
                        // TODO 好像有什么其他简单的加法
                        double s = 0D;
                        int len = learnHistories.size();
                        for (LearnHistoryDto learnHistoryDto : learnHistories) {
                            if (learnHistoryDto.getLearnHistory() != null) {
                                s += learnHistoryDto.getLearnHistory().getSchedule();
                            }

                        }
                        if ((s / len) == 1) {
                            courseHistory.setStatus(2);
                        }
                        courseHistory.setSchedule(s / len);

                        courseHistoryService.modifyCourseHistory(courseHistory);
                    }
                }
            }
        }
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    // 我的学习历史一级
    @ResponseBody
    @RequestMapping(value = "/courseHistoryList", method = RequestMethod.GET)
    public Map<String, Object> courseHistoryList(Integer pageIndex, Integer pageSize, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        PageList<CourseHistoryDto> courseHistories = learnHistoryService.pageCourseHistoryDtoByParams(pageIndex,
                pageSize == null ? DsConstant.PAGESIZE_FOUR : pageSize, userId);

        map.put("list", courseHistories.getList());
        map.put("page", courseHistories.getPageData());
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    // 我的学习历史二级
    @ResponseBody
    @RequestMapping(value = "/{courseId}/learnHistoryList", method = RequestMethod.GET)
    public Map<String, Object> learnHistoryList(@PathVariable("courseId") Long courseId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        List<LearnHistoryDto> learnHistorys = learnHistoryService.getLearnHistoryDtoByParams(userId, courseId);

        map.put("list", learnHistorys);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteCollection", method = RequestMethod.POST)
    public Map<String, Object> deleteCollection(Long collectionId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        Collection collection = collectionService.getByCollectionIdUserId(collectionId, userId);
        if (collection != null) {
            collectionService.deleteCollection(collection);
        }
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/addCollection", method = RequestMethod.POST)
    public Map<String, Object> addCollection(Long relationId, int type, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        Collection collection = collectionService.getByIds(relationId, userId, type);
        if (collection == null) {
            collection = new Collection(relationId, userId, type);
            collectionService.addCollection(collection);
        }
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/collectionList", method = RequestMethod.GET)
    public Map<String, Object> collectionList(Integer pageIndex, Integer pageSize, int type, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        PageList<CollectionDto> collections = collectionService.pageDtoByUserId(pageIndex, pageSize == null ? DsConstant.PAGESIZE_FOUR : pageSize, userId, type);
        map.put("list", collections.getList());
        map.put("page", collections.getPageData());
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/addShoppingCart", method = RequestMethod.POST)
    public Map<String, Object> addShoppingCart(Long goodsId, int type, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        ShoppingCart cart = shoppingCartService.getShoppingCartByIds(goodsId, userId, type);

        // 购物车中存在，则不添加
        if (cart == null) {
            // 订单中存在， （未付款，完成）则不添加
            Order order = orderService.getOrderByGoodsId(goodsId, type, userId);
            if (order == null) {
                cart = new ShoppingCart(goodsId, type, 1, userId);

                shoppingCartService.addShoppingCart(cart);
                return map;
            } else {
                map.put(DsConstant.CODE, DsConstant.CODE_ADD_SHOPPING_CART_ORDER_ERROR);
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_ADD_SHOPPING_CART_ORDER_ERROR);
            }
        } else {
            map.put(DsConstant.CODE, DsConstant.CODE_SHOPPING_CART_EXIST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_SHOPPING_CART_EXIST);
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteShoppingCart", method = RequestMethod.POST)
    public Map<String, Object> deleteShoppingCart(Long cartId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        ShoppingCart cart = shoppingCartService.getShoppingCartByCartIdUserId(cartId, userId);

        if (cart != null) {
            shoppingCartService.deleteShoppingCart(cart);
        }
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/shoppingCart", method = RequestMethod.GET)
    public Map<String, Object> shoppingCartList(Integer pageIndex, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        List<ShoppingCartDto> carts = shoppingCartService.getDtoByUserId(pageIndex, userId);
        map.put("list", carts);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public Map<String, Object> addOrder(int type, Long goodsId, Integer goodsType, String cartIds, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        String orderNum = CommonUtils.getOrderNum();
        if (type == 0) {
            // 商品直接购买，不经过购物车
            orderService.addOrderByGoodsIdType(orderNum, goodsId, goodsType, userId);
        } else {
            orderService.addOrderByCartIds(orderNum, cartIds, userId);
        }

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        map.put("orderNum", orderNum);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
    public Map<String, Object> cancelOrder(String orderNum, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        Order order = orderService.getOrderByOrderNum(orderNum);

        if (order.getUserId() == userId) {
            if (order.getStatus() == Order.Status.SUCCESS) {
                map.put(DsConstant.CODE, DsConstant.CODE_ORDER_COMPLETE_ERROR);
                map.put(DsConstant.CODE, DsConstant.MESSAGE_ORDER_COMPLETE_ERROR);
                return map;
            }
            order.setStatus(Order.Status.CANCEL);
            orderService.modifyOrder(order);
        }

        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/orderList", method = RequestMethod.GET)
    public Map<String, Object> orderList(Integer pageIndex, Integer pageSize, Integer status, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        PageList<OrderDto> orders = orderService.getOrderDtoByUserId(pageIndex, pageSize == null ? DsConstant.PAGESIZE_FOUR : pageSize, userId, status == null ? 0 : status);
        map.put("list", orders.getList());
        map.put("page", orders.getPageData());
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/buyList", method = RequestMethod.POST)
    public Map<String, Object> buyList(Integer pageIndex, Integer pageSize, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        PageList<BuyHistoryDto> buys = buyHistoryService.getBuyHistoryDtoByUserId(pageIndex, pageSize == null ? DsConstant.PAGESIZE_FOUR : pageSize, userId);
        map.put("list", buys.getList());
        map.put("page", buys.getPageData());
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/changeOrderStatus", method = RequestMethod.GET)
    public Map<String, Object> changeOrderStatus(String orderNum, int status) {
        Map<String, Object> map = new HashMap<>();
        Order order = orderService.getOrderByOrderNum(orderNum);
        if (order == null) {
            return map;
        }
        if (status == 2) {
            // 添加我的购买记录
            List<OrderDetail> details = orderDetailService.getOrderDetailByOrderNum(orderNum);
            if (!StringUtils.isEmptyList(details)) {
                for (OrderDetail orderDetail : details) {
                    BuyHistory buy = new BuyHistory(orderDetail.getUserId(), orderDetail.getGoodsId(), orderDetail.getGoodsType());
                    buyHistoryService.addBuyService(buy);

                    // 商品的购买记录+1
                    if (buy.getGoodsType() == 1) {
                        courseService.addSaleNum(buy.getGoodsId());
                    }

                }
            }
        }
        order.setStatus(status);
        orderService.modifyOrder(order);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.GET)
    public Map<String, Object> forgetPassword(String email) {
        Map<String, Object> map = new HashMap<>();
        try {
            EmailUitl.sendEmail1(email);
            map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(DsConstant.CODE, DsConstant.CODE_EMAIL_SEND_ERROR);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_EMAIL_SEND_ERROR);
            return map;
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/forgetPasswordConfirm", method = RequestMethod.GET)
    public void forgetPasswordConfirm(String action, String code, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        if (DsConstant.FORGET_PASSWORD.equals(action)) {
            String decode = new String(Base64.getDecoder().decode(code));
            System.out.println(decode);
            JSONObject jsonObject = JSONObject.parseObject(decode);
            String email = jsonObject.getString("email");
            User user = userService.getUserByEmail(email);

            if (user != null) {
                long expDate = jsonObject.getLongValue("expDate");
                if (new Date().before(new Date(expDate))) {
                    String token = ValidationUtils.createJWT(user, ValidationUtils.DAY_ONE);
                    map.put("token", token);
                    map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
                } else {
                    map.put(DsConstant.CODE, DsConstant.CODE_LINK_LOST);
                    map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_LINK_LOST);
                }
            } else {
                map.put(DsConstant.CODE, DsConstant.CODE_USER_LOST);
                map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USER_LOST);
            }

        } else {
            map.put(DsConstant.CODE, DsConstant.CODE_LINK_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_LINK_LOST);
        }
        String json = JSON.toJSONString(map);

        String html = HtmlModal.getHtmlModal(json, HtmlModal.PASSWORD);

        CommonUtils.responseOutHtml(response, html);
    }

    @ResponseBody
    @RequestMapping(value = "/forgetPasswordChange", method = RequestMethod.POST)
    public Map<String, Object> forgetPasswordChange(String newPassword, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);

        User user = userService.getUserByUserId(userId);
        if (user == null) {
            map.put(DsConstant.CODE, DsConstant.CODE_USER_LOST);
            map.put(DsConstant.MESSAGE, DsConstant.MESSAGE_USER_LOST);
            return map;
        }

        user.setPassword(CommonUtils.MD5(newPassword));

        userService.updataUser(user);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/buyHistory")
    public Map<String, Object> buyHistory(Integer pageIndex, Integer pageSize, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        long userId = StringUtils.parseLong(String.valueOf(request.getAttribute("userId")), 0);
        PageList<BuyHistoryDto> list = buyHistoryService.getBuyHistoryDtoByUserId(pageIndex, pageSize == null ? DsConstant.PAGESIZE_FOUR : pageSize, userId);
        map.put("list", list.getList());
        map.put("page", list.getPageData());
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return map;
    }

}
